<!--
 * @Author: Bennty
 * @Date: 2024-10-25 11:18:43
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-10-29 16:27:23
 * @Description: 请填写简介
-->
<template>
<div class="p-2">
        <el-row :gutter="20">
            <el-col :span="12">
                <el-card class="product-info">
                    <el-form :model="productInfo" ref="productInfoRef" :rules="formRules">
                        <el-row >
                            <el-col :span="12">
                                <el-form-item label="产品大类" prop="productCategoriesType">
                                    <el-select v-model="selectedCategory" value-key="value" placeholder="请选择">
                                        <el-option v-for="item in total_catagory" :key="item.value" :label="item.label" :value="item"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="产品小类" prop="productSubcategoryType">
                                    <el-select v-model="selectedSubCategory" value-key="value" placeholder="请选择">
                                        <el-option v-for="item in single_catagory" :key="item.value" :label="item.label" :value="item"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="30">
                            <el-col :span="12">
                                <el-form-item label="产品名称" prop="bomName">
                                    <el-input v-model="productInfo.bomName" placeholder="请输入"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="单价" prop="bomPrice">
                                    <el-input type="number" v-model="productInfo.bomPrice" placeholder="请输入">
                                        <template #append>元</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="8">
                                <el-form-item label="纸箱" prop="paperBoxType">
                                    <el-select v-model="productInfo.paperBoxType" placeholder="请选择">
                                        <el-option v-for="item in cartons" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="5">
                                <el-form-item label="箱规" prop="boxGauge">
                                    <el-input type="number" :min="0" v-model.number="productInfo.boxGauge">
                                        <template #append>/箱</template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="3" :offset="1">
                                <el-form-item label="喷码" prop="sprayCoding">
                                    <el-checkbox v-model="productInfo.sprayCoding" :true-label="'1'" :false-label="'0'"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="5">
                                <el-row>
                                    <el-col :span="18">
                                        <el-form-item prop="packingMethod">
                                            <el-select v-model="productInfo.packingMethod" :disabled="!isPackage" @change="handleIsPackageChange">
                                                <el-option v-for="item in package_method" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="3" :offset="2">
                                        <el-checkbox v-model="isPackage" :true-value="true" :false-value="false"/>
                                    </el-col>
                                </el-row>
                                
                            </el-col>
                        </el-row>
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="productInfo.remark" type="textarea" placeholder="请输入" maxlength="128" show-word-limit></el-input>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card class="product-detail-info">
                    <el-form>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="现有库存">
                                    <span :style="{fontWeight:'bolder'}">{{ productInfo.currentInventory || '0箱 共计0盒' }}</span>
                                </el-form-item>
                                <el-form-item label="成本分析">
                                    <span>
                                        <span :style="{fontWeight:'bolder'}">{{ costPerBox }}元</span>/盒
                                    </span>
                                </el-form-item>
                                <el-form-item label="组装工费">
                                    <el-row :gutter="10">
                                        <el-col :span="12">
                                            <el-input v-model.number="laborCost.price" type="number" placeholder="工费">
                                                <template #append>/盒</template>
                                            </el-input>
                                        </el-col>
                                        <el-col :span="11">
                                            <el-input v-model.number="laborCost.integral" type="number" placeholder="积分"  />
                                        </el-col>
                                    </el-row>
                                </el-form-item>
                                <el-form-item :label="`${packagingName || '包装'}工费`" v-show="isPackage">
                                    <el-row :gutter="10" >
                                        <el-col :span="12">
                                            <el-input v-model.number="packingCost.price" type="number" placeholder="工费" :disabled="!productInfo.packingMethod" >
                                                <template #append>/盒</template>
                                            </el-input>
                                        </el-col>
                                        <el-col :span="11">
                                            <el-input v-model.number="packingCost.integral" type="number" placeholder="积分" :disabled="!productInfo.packingMethod" />
                                        </el-col>
                                    </el-row>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="效果图">
                                    <!-- <el-image style="width: 200px; height: 152px" :src="productDetailInfo.image"></el-image> -->
                                    <el-upload
                                        class="showImage-uploader"
                                        ref="showImageRef"
                                        :action="uploadImgUrl" 
                                        :headers="headers" 
                                        :show-file-list="false"
                                        :on-success="handleShowImageSuccess"
                                        :before-upload="beforeShowImageUpload"
                                    >
                                        <img style="width: 200px; height: 152px" v-if="showImageUrl" :src="showImageUrl" class="showImage" />
                                        <el-icon v-else-if="!showImageUrl && showImageUploading"><Loading /></el-icon>
                                        <el-icon v-else class="showImageuploader-icon-form" ><Plus /></el-icon>
                                    </el-upload>
                                </el-form-item>
                                <el-form-item label="源文件">
                                    <el-upload
                                        ref="sourceFileRef"
                                        :action="uploadImgUrl"
                                        :headers="headers"
                                        :auto-upload="true"
                                        :show-file-list="false"
                                        :on-success="handleSourceFileSuccess"
                                        :before-upload="beforeSourceFileUpload"
                                    >
                                        <el-button link type="primary" v-if="sourceFile">{{  sourceFile.fileName }}</el-button>
                                        <el-button link type="primary" :loading="sourceFileUploading" v-else>点击上传源文件</el-button>
                                    </el-upload>
                                    <!-- <el-button link type="primary" @click="handleClickSourceFile">{{ productDetailInfo.sourceFile }}</el-button> -->
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-card>
            </el-col>
        </el-row>
        <el-card class="materials-card">
            <template #header>
                <h2>半成品：</h2>
            </template>
            <el-row class="prepared-product-list">
                <el-col :span="4" v-for="(item,index) in preparedProducts" :key="index">
                    <div class="prepared-product"  >
                        <el-image class="prepared-product-img" style="width: 178px; height: 178px; border-radius:10px" :src="item.imageUrl"></el-image>
                        <p class="product-info-text">{{item.specsDetail}}</p>
                        <p class="product-info-text">{{ `￥ ${item.number * item.price}` }}</p>
                        <div class="delete" @click="handleDeletePreparedProduct(index)">
                            <el-icon class="delete-icon"><SemiSelect /></el-icon>
                        </div>
                    </div>
                </el-col>
                <el-col :span="4">
                    <el-icon class="avatar-uploader-icon" @click="handleClickAddPreparedProduct"><Plus /></el-icon>
                </el-col>
            </el-row>
        </el-card>
        <el-card class="materials-card">
            <template #header>
                <h2>辅材：</h2>
            </template>
                <el-row class="prepared-product-list">
                    <el-col :span="4" class="prepared-product"  v-for="(item,index) in auxiliaries" :key="index">
                        <el-image class="prepared-product-img" style="width: 178px; height: 178px;border-radius:10px" :src="item.imageUrl"></el-image>
                        <p class="product-info-text">{{item.specsDetail}}</p>
                        <p class="product-info-text">{{ `￥ ${item.number * item.price}` }}</p>
                        <div class="delete" @click="handleDeleteAuxiliaries(index)">
                            <el-icon class="delete-icon"><SemiSelect /></el-icon>
                        </div>
                    </el-col>
                    <el-col :span="4">
                        <el-icon class="avatar-uploader-icon" @click="handleClickAddAuxiliaries"><Plus /></el-icon>
                    </el-col>
                </el-row>
        </el-card>
        <div class="dialog-footer">
            <el-button  type="primary" size="large" @click="handleSubmit(productInfoRef)" >确 定</el-button>
            <el-button size="large" @click="handleCancel" >取 消</el-button>
        </div>
        <el-image-viewer v-if="showViewer" @close="handleCloseViewer" :url-list="urlList"></el-image-viewer>
        <el-dialog v-model="addPreparedProductVisible" title="半成品添加" width="25%" @close="handleCloseAddPreparedProduct">
            <el-form :model="preparedProductFormData" ref="preparedProductRef">
                <el-row>
                    <el-col :span="12">
                        <el-form-item>
                            <el-select v-model="selectedPreparedProduct" filterable value-key="id" placeholder="请选择">
                                <el-option v-for="item in preparedList" :key="item.id" :label="item.specsDetail" :value="item"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="需求数量" prop="number">
                            <el-input-number v-model.number="preparedProductFormData.number"  />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="材料小类" prop="part">
                    {{ selectedPreparedProduct?.productSubcategoryName }}
                    <!-- <el-select v-model="preparedSubType" value-key="id">
                        <el-option v-for="item in preparedSubTypes" :key="item.id" :label="item.subclassName" :value="item"></el-option>
                    </el-select> -->
                </el-form-item>
                
                <el-form-item prop="image">
                    <el-upload class="avatar-uploader-form" :action="uploadImgUrl" :headers="headers" :show-file-list="false"  disabled
                    >
                        <img style="width: 100%" v-if="preparedProductImageUrl" :src="preparedProductImageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon-form"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button  type="primary" @click="handleSubmitAddPreparedProduct">确 定</el-button>
                    <el-button @click="handleCloseAddPreparedProduct">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="addAuxiliariesVisible" title="添加辅材" width="25%" @close="handleCloseAddAuxiliaries">
            <el-form :model="auxiliaryFormData" ref="auxiliariesRef">
                <el-row>
                    <el-col :span="12">
                        <el-form-item prop="selectedAuxiliary">
                            <el-select v-model="selectedAuxiliary" filterable value-key="id" placeholder="请选择">
                                <el-option v-for=" item in auxiliariesList" :key="item.id" :label="item.specsDetail" :value="item"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="需求数量" prop="number">
                            <el-input type="number" v-model.number="auxiliaryFormData.number" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="材料大类" prop="majorType">
                            <!-- <el-select v-model="majorType">
                                <el-option v-for="item in typeList" :key="item.id" :label="item.majorName" :value="item.majorType"></el-option>
                            </el-select> -->
                            {{ selectedAuxiliary?.productCategoriesName }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="材料小类" prop="subType">
                            <!-- <el-select v-model="subType">
                                <el-option v-for="item in subTypeList" :key="item.id" :label="item.subclassName" :value="item.subclassType"></el-option>
                            </el-select> -->
                            {{ selectedAuxiliary?.productSubcategoryName }}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item prop="image">
                    <el-upload class="avatar-uploader-form" 
                        :action="uploadImgUrl" 
                        :headers="headers" 
                        :show-file-list="false" 
                        :disabled="true"
                    >
                        <img style="width: 100%" v-if="auxiliaryImage" :src="auxiliaryImage" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon-form"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button  type="primary" @click="handleSubmitAddAuxiliaries()">确 定</el-button>
                    <el-button @click="handleCloseAddAuxiliaries">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import type { FormInstance, UploadInstance, UploadProps, FormRules } from 'element-plus';
import { globalHeaders } from "@/utils/request";
import { getBOMDetailApi, editBomApi } from '@/api/sj/warehouse/BOM'; 
import { getAuxiliaryListApi } from '@/api/sj/warehouse/auxiliary';
import { getSemiProductListApi } from '@/api/sj/warehouse/productInventory';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { total_catagory,single_catagory,cartons,package_method } = toRefs<any>(proxy?.useDict('total_catagory','single_catagory','cartons','package_method'));
const router = useRouter();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);

const productInfoRef = ref<FormInstance>();
const isPackage =ref(true);
const showImageRef = ref<UploadInstance>();
const showImageUploading = ref(false);
const showImageUrl = ref<string | undefined>();
const sourceFileRef = ref<UploadInstance>();
const sourceFileUploading = ref(false);
const sourceFile = ref<any>();
const packagingName = ref<string | undefined>();
const laborCost = ref<any>({
    price: undefined,
    integral: undefined,
    type: 1
});
const packingCost = ref<any>({
    price: undefined,
    integral: undefined,
    type: 2
});
const costPerBox = ref<number>(0);


const showViewer = ref(false);
const urlList = ref<string[]>([]);
const addPreparedProductVisible = ref(false);
const preparedProductRef = ref<FormInstance>();
const preparedList = ref<any[]>([]);
const preparedProducts = ref<any[]>([]);
const selectedPreparedProduct = ref<any>();
const preparedProductImageUrl = ref<any>();

const addAuxiliariesVisible = ref(false);
const auxiliariesList = ref<any[]>([]);
const auxiliariesRef = ref<FormInstance>();
const auxiliaries = ref<any[]>([]);
const selectedAuxiliary = ref<any>();
const auxiliaryImage = ref(undefined);

const selectedCategory = ref<any>();
const selectedSubCategory = ref<any>();

const data = reactive({
    productInfo:{
        id: undefined,
        bomName: undefined,
        bomPrice: undefined,
        paperBoxType: undefined,
        boxGauge:undefined,
        sprayCoding: undefined,
        packingMethod: undefined,
        remark: undefined,
        bomType: 1,
        renderingsUrl: undefined,
        sourceFile: undefined,
        currentInventory: undefined
    },
    preparedProductFormData:{
        semiProductId: undefined,
        number: 1,
        imageUrl: undefined,
        price: undefined,
        specsDetail: undefined,
        bomId: undefined
    },
    auxiliaryFormData:{
        auxiliaryMaterialId: undefined,
        number: 1,
        imageUrl: undefined,
        price: undefined,
        specsDetail: undefined,
        bomId: undefined
    }
});

const { productInfo,preparedProductFormData,auxiliaryFormData } = toRefs(data);

const checkBoxGauge = (rule: any, value: any, callback: any) => {
    setTimeout(() => {
        if (!Number.isInteger(value)) {
            callback(new Error('箱规为整数'))
            } else {
            if (value <= 0) {
                callback(new Error('箱规必须大于0'))
            } else {
                callback()
            }
        }
    }, 500)
};

const formRules = reactive<FormRules>({
    boxGauge:[
        {validator: checkBoxGauge, trigger: 'blur'}
    ]
});

const getBOMDetail = async () => {
    const bomId = router.currentRoute.value.fullPath.split('/')[3];
    const { data } = await getBOMDetailApi(bomId);
    productInfo.value.id = data.id;
    productInfo.value.bomName = data.bomName;
    productInfo.value.bomPrice = data.bomPrice;
    productInfo.value.boxGauge = data.boxGauge;
    productInfo.value.paperBoxType = data.paperBoxType;
    productInfo.value.packingMethod = data.packingMethod;
    productInfo.value.remark = data.remark;
    productInfo.value.currentInventory = data.currentInventory;
    showImageUrl.value = data.renderingsUrl;
    sourceFile.value = {fileName: '源文件', url:data.sourceFile};
    productInfo.value.sprayCoding = data.sprayCoding;
    const preparedProductsList = data.bomRelatSemiVos.map((item:any)=>{
        return {
            ...item,
            bomId: data.id
        }
    });
    preparedProducts.value = [...preparedProductsList];
    const auxiliariesList = data.auxiliaryMaterialsVos.map((item: any)=>{
        return {
            ...item,
            bomId: data.id
        }
    });
    auxiliaries.value = [...auxiliariesList];
    const laborInfo = data.laborCostVos.filter((item: any)=>item.type == 1)[0];
    laborCost.value = {...laborInfo, bomId: data.id,type: 1};
    const packageInfo = data.laborCostVos.filter((item: any)=>item.type == 2)[0];
    packingCost. value = {...packageInfo, bomId: data.id, type: 2};
    const totalCatagory = total_catagory.value.filter((item:any)=>item.value == data.productCategoriesType)[0];
    const subCatagory = single_catagory.value.filter((item:any)=>item.value == data.productSubcategoryType)[0];
    selectedCategory.value = {...totalCatagory};
    selectedSubCategory.value = {...subCatagory};
};

/** 不需要包装时清空包装方式 */
watch(()=>isPackage.value, (newData)=>{
    if(!newData){
        productInfo.value.packingMethod = undefined;
        packagingName.value = undefined;
        packingCost.value = 0;
    };
});

const handleIsPackageChange = (value: any) => {
    const selectedPackageMethod = package_method.value.filter((item: any)=>{
        return item.value == value;
    })[0];
    packagingName.value = selectedPackageMethod.label;
};

/** 上传效果图 */
const handleShowImageSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    showImageUrl.value = response.data.url;
    showImageUploading.value = false;
};

const beforeShowImageUpload: UploadProps['beforeUpload'] = (rawFile) => {
    showImageUploading.value = true;
    if (!['image/jpeg', 'image/png'].includes(rawFile.type)) {
        ElMessage.error('必须上传jpg，png格式图片!');
        showImageUploading.value = false;
        return false;
    } else if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error('不可上传大于10MB的图片!');
        showImageUploading.value = false;
        return false;
    };
    return true;
};

/** 上传源文件 */
const handleSourceFileSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    sourceFile.value = response.data;
    sourceFileUploading.value = false;
};

const beforeSourceFileUpload: UploadProps['beforeUpload'] = () => {
    sourceFileUploading.value = true;
};

/** 获取所有辅材 */
const getAuxiliaryList = async () => {
    const { rows } = await getAuxiliaryListApi({
        pageNum: 1,
        pageSize: 999
    });
    auxiliariesList.value = rows;
};

/** 获取半成品材料列表 */
const getSemiProductList = async () => {
    const result = await getSemiProductListApi({
        pageNum: 1,
        pageSize: 999
    });
    //@ts-ignore
    preparedList.value = result.dataList.records;
};

const handleCloseViewer = ()=>{
    urlList.value = [];
    showViewer.value = false;
};

/** 点击添加半成品 */
const handleClickAddPreparedProduct = ()=>{
    if(preparedProducts.value.length<6){
        addPreparedProductVisible.value = true;
    }else{
        proxy?.$modal.msgWarning("半成品最多可加6个");
    };
};

/** 关闭添加半成品 */
const handleCloseAddPreparedProduct = ()=>{
    addPreparedProductVisible.value = false;
    preparedProductRef.value?.resetFields();
    selectedPreparedProduct.value = undefined;
    preparedProductImageUrl.value = undefined;
};

/** 确定选中的半成品 */
watch(()=>selectedPreparedProduct.value, (newData)=>{
    if(newData){
        preparedProductFormData.value.semiProductId = newData.id;
        preparedProductImageUrl.value = newData.imageUrl;
        preparedProductFormData.value.imageUrl = newData.imageUrl;
        preparedProductFormData.value.price = newData.price;
        preparedProductFormData.value.specsDetail = newData.specsDetail;
        preparedProductFormData.value.bomId = productInfo.value.id;
    }else{
        preparedProductFormData.value.semiProductId = undefined;
        preparedProductImageUrl.value = undefined;
        preparedProductFormData.value.imageUrl = undefined;
        preparedProductFormData.value.price = undefined;
        preparedProductFormData.value.specsDetail = undefined;
    };
},{deep: true});

/** 点击提交添加半成品 */
const handleSubmitAddPreparedProduct = ()=>{
    if(preparedProductFormData.value.semiProductId){
        preparedProducts.value.push({...preparedProductFormData.value});
        handleCloseAddPreparedProduct();
    }else{
        proxy?.$modal.msgError('未选择半成品');
    };
};

/** 去掉半成品列表中已选中的半成品 */
watch(()=>preparedProducts.value,async (newData)=>{
    if(newData.length > 0){
        const result = await getSemiProductListApi({
            pageNum: 1,
            pageSize: 999
        });
        //@ts-ignore
        const filterData = result.dataList.records.filter((row: any)=>{
            return !newData.some((preparedProduct)=>preparedProduct.semiProductId == row.id);
        });
        preparedList.value = filterData;
    }else{
        getSemiProductList();
    };
},{deep: true});

/** 点击添加辅材*/
const handleClickAddAuxiliaries = ()=>{
    if(preparedProducts.value.length < 6){
        addAuxiliariesVisible.value = true;
    }else{
        proxy?.$modal.msgWarning("辅材最多可加6个");
    };
};

/** 确定选中的辅材，填充数据 */
watch(()=>selectedAuxiliary.value, (newData)=>{
    if(newData){
        auxiliaryFormData.value.auxiliaryMaterialId = newData.id;
        auxiliaryImage.value = newData.imageUrl;
        auxiliaryFormData.value.imageUrl = newData.imageUrl;
        auxiliaryFormData.value.price = newData.price;
        auxiliaryFormData.value.specsDetail = newData.specsDetail;
        auxiliaryFormData.value.bomId = productInfo.value.id;
    }else{
        auxiliaryFormData.value.auxiliaryMaterialId = undefined; 
        auxiliaryImage.value = undefined;
        auxiliaryFormData.value.imageUrl = undefined;
        auxiliaryFormData.value.price = undefined;
        auxiliaryFormData.value.specsDetail = undefined;
    };
    
},{deep: true});

/** 关闭添加辅材 */
const handleCloseAddAuxiliaries = ()=>{
    addAuxiliariesVisible.value = false;
    auxiliariesRef.value?.resetFields();
    selectedAuxiliary.value = undefined;
};

/** 点击提交辅材 */
const handleSubmitAddAuxiliaries = ()=>{
    if(auxiliaryFormData.value.auxiliaryMaterialId){
        auxiliaries.value.push({...auxiliaryFormData.value});
        handleCloseAddAuxiliaries();
    }else{
        proxy?.$modal.msgError('未选择辅材');
    };
};

/** 去掉辅材列表中已选中的辅材 */
watch(()=>auxiliaries.value,async (newData)=>{
    // console.log(newData);
    if(newData.length > 0){
        const { rows } = await getAuxiliaryListApi({
            pageNum: 1,
            pageSize: 999
        });
        const filterData = rows.filter((row: any)=>{
            return !newData.some((auxiliary)=>auxiliary.auxiliaryMaterialId === row.id)
        });
        auxiliariesList.value = filterData;
    }else{
        getAuxiliaryList();
    };
},{deep: true});

//删除半成品
const handleDeletePreparedProduct = (index:number)=>{
    preparedProducts.value.splice(index,1);
};

//删除辅材
const handleDeleteAuxiliaries = (index:number)=>{
    auxiliaries.value.splice(index,1);
};

/** 提交添加bom */
const handleSubmit = (formEl: FormInstance | undefined) => {
    if(!formEl) return;
    formEl.validate(async (valid)=>{
        if(valid){
            const submitData = {
                ...productInfo.value,
                sourceFile: sourceFile.value?.url || undefined,
                renderingsUrl: showImageUrl.value || undefined,
                productCategoriesType: selectedCategory.value?.value || undefined,
                productCategoriesName: selectedCategory.value?.label || undefined,
                productSubcategoryType: selectedSubCategory.value?.value || undefined,
                productSubcategoryName: selectedSubCategory?.value.label || undefined,
                relatSemiBos: [...preparedProducts.value],
                relatAuxiliaryMaterialsBos: [...auxiliaries.value],
                relatLaborCostBos: [{...laborCost.value,bomId: productInfo.value.id},{...packingCost.value,bomId: productInfo.value.id}]
            };
            if((productInfo.value.bomPrice || 0) > costPerBox.value){
                const { code } = await editBomApi(submitData);
                if(code == 200){
                    proxy?.$modal.msgSuccess('修改BOM成功');
                    handleCancel();
                };
            }else{
                proxy?.$modal.msgError('单价必须大于成本');
            }; 
        }else{
            console.log('error submit!')
        }
    });
    
};

/** 取消添加bom */
const handleCancel = () => {
    productInfoRef.value?.resetFields();
    selectedCategory.value = undefined;
    selectedSubCategory.value = undefined;
    showImageRef.value?.clearFiles();
    sourceFileRef.value?.clearFiles();
    laborCost.value = {
        price: undefined,
        integral: undefined,
        type: 1,
    };
    packingCost.value = {
        price: undefined,
        integral: undefined,
        type: 2
    };
    router.back();
};

onMounted(()=>{
    getBOMDetail();
    getAuxiliaryList();
    getSemiProductList();
});

/** 计算成本 */
watch(()=>[
    preparedProducts.value,
    auxiliaries.value,
    laborCost.value,
    packingCost.value
],(newData)=>{
    const [ preparedProducts, auxiliaries, laborCost, packingCost ] = newData;
    let preparedCost = 0;
    /** 半成品成本 计算*/
    if(preparedProducts){
        // @ts-ignore
        preparedProducts.forEach((item: any)=>{
            preparedCost += item.number * item.price
        });
    };
    let auxiliaryCost = 0;
    /** 辅材成本计算 */
    if(auxiliaries){
        // @ts-ignore
        auxiliaries.forEach((item: any)=>{
            auxiliaryCost += item.number * item.price
        });
    };
    // console.log(preparedCost, auxiliaryCost, laborCost.price, packingCost.price);
    // @ts-ignore
    let totalCost = preparedCost + auxiliaryCost + (Number(laborCost.price) || 0) + (Number(packingCost.price) || 0);
    costPerBox.value = totalCost;
},{deep: true});

</script>

<style lang="scss" scoped>
.avatar-uploader {
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    margin-left:5px;
    border-radius: 10px;
    border: 1px dashed black;
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    &:hover{
        cursor: pointer;
    }
}

::v-deep(.el-upload){
    width: 100% !important;
}

.materials-card{
    margin-top: 20px;
}
.prepared-product-list{
    // display: flex;
    .prepared-product{
        position: relative;
    }
    .product-info-text{
        margin-top: 5px;
        margin-bottom: 5px;
        font-size: 15px;
    }
    .prepared-product-img:nth-child(n+2){
        margin-left: 50px;
        border: dashed 1px grey;
    }
    .delete{
        position: absolute;
        left: 129px;
        top: 0px;
        width: 0;
        height: 0;
        border-style:solid;
        border-color: transparent #ff0000;
        border-width: 0 50px 50px 0;
        border-radius: 10px;
        .delete-icon{
            position: absolute;
            font-size: 20px;
            color: #ffffff;
            right: -40px;
            top: 5px;
        }
        &:hover{
            cursor: pointer;
        }
    }
}

.avatar-uploader-form{
    margin-left:5px;
    border-radius: 10px;
    border: 1px dashed black;
    font-size: 28px;
    color: #8c939d;
    width: 100%;
    height: 178px;
    text-align: center;
    .avatar{
        height: 178px;
    }
}

.avatar-uploader-icon-form{
    font-size: 28px;
    color: #8c939d;
    // width: 100%;
    height: 178px;
    text-align: center;
}

.showImage-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.showImage-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.showImage-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    border: 1px dashed var(--el-border-color);
}

.dialog-footer{
    margin-top: 15px;
    display: flex;
    justify-content: center;
}
</style>